#!/usr/bin/env groovy

def call(Map config = [:]) {

    def podTemplate = utilities.pod_template()
    pipeline {
        agent {
            kubernetes {
                yaml podTemplate
            }
        }
        environment {
            EU_AWS_ACCESS_KEY_ID = credentials('EU_AWS_ACCESS_KEY_ID')
            EU_AWS_SECRET_ACCESS_KEY = credentials('EU_AWS_SECRET_ACCESS_KEY')
            DEPLOY_ACCOUNT = '396015846097'
            AWS_DEFAULT_REGION = 'cn-north-1'
        }
        stages {
            stage('Start Notification') {
                steps {
                    container('cdk') {
                        script {
                            utilities.pipeline_notification('START')
                        }
                    }
                }
            }
            stage('Build && test') {
                steps {
                    container('cdk') {
                        script {
                            try {
                                //Switch to App Account
                                utilities.build_script()
                            } catch (Exception e) {
                                utilities.pipeline_notification('FAILED', e.toString())
                                error('Stopping early…')
                            }
                        }
                    }
                }
            }
            stage('Deploy to dev ENV') {
                steps {
                    script {
                        container('cdk') {
                            try {
                                //Switch to App Account
                                utilities.assum_role("APP_ACCOUNT_ROLE")
                                env.STAGE = 'dev'
                                env.TAG = 'latest'
                                env.SEMVER = 'semver'
                                utilities.deploy_script()
                            } catch (Exception e) {
                                utilities.pipeline_notification('FAILED', e.toString())
                                error('Stopping early…')
                            }
                        }
                    }
                }
            }
            stage('End Notification') {
                steps {
                    container('cdk') {
                        script {
                            utilities.pipeline_notification('SUCCESS')
                        }
                    }
                }
            }
        }
    }
}
